const tbody = document.querySelector('tbody');
const addform = document.querySelector('#addModal form');
const upadteform = document.querySelector('#updateModal form');

// 查询全部学生
getstudentList()
function getstudentList() {
  axios.get('/student/list').then(res => {
    if (res.data.code === 0) {
      const arr = res.data.data

      const oHmtl = arr.reduce((h, v) => h + `
      <tr>
        <th scope="row">${v.id}</th>
        <td>${v.name}</td>
        <td>${v.age}</td>
        <td>${v.sex}</td>
        <td>${v.group}</td>
        <td>${v.phone}</td>
        <td>${v.salary}</td>
        <td>${v.truesalary}</td>
        <td>${v.province}${v.city + v.county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm update" data-id="${v.id}">修改</button>
          <button type="button" class="btn btn-danger btn-sm delectbtn" data-id="${v.id}">删除</button>
        </td>
      </tr>
      `, '')
      tbody.innerHTML = oHmtl
    }
  })
}

// 查询省级
function renderSelect(url, params, dom, text, select) {
  axios.get(url, { params }).then(res => {
    dom.innerHTML = res.data.reduce((h, v) => h + `
    <option value="${v}">${v}</option>
    `, `<option value="">--${text}--</option>`)

    dom.value = select
  })
}

function initSelect(selector) {
  const province = document.querySelector(`${selector} [name=province]`);
  const city = document.querySelector(`${selector} [name=city]`);
  const county = document.querySelector(`${selector} [name=county]`);
  renderSelect('/geo/province', {}, province, '省')
  province.addEventListener("change", function () {
    renderSelect('/geo/city', {
      pname: province.value,
    }, city, '市')
  })
  city.addEventListener("change", function () {
    renderSelect('/geo/county', {
      pname: province.value,
      cname: city.value
    }, county, '县')
  })
}
// 初始化提交表单， 下拉框
initSelect('#addModal')
// 初始化编辑表单， 下拉框
initSelect('#updateModal')
// 提交表单
addform.addEventListener("submit", function (e) {
  e.preventDefault();
  // 获取表单内容
  const data = $(addform).serialize()
  console.log(data);
  axios.post('/student/add', data).then(res => {
    if (res.data.code === 0) {
      toastr.success(res.data.message)
      addform.reset()
      // 关闭模态框
      $('#addModal').modal('hide');
      // 获取最新的数据
      getstudentList();
    }
  })
})
// 点击修改按钮事件
tbody.addEventListener("click", function (e) {
  if (e.target.nodeName === 'BUTTON' && e.target.classList.contains('update')) {
    $('#updateModal').modal('show');
    const id = e.target.dataset.id
    axios.get('/student/one', {
      params: {
        id: id
      }
    }).then(res => {
      if (res.data.code === 0) {
        const obj = res.data.data
        console.log(obj);
        // 遍历obj 给表单添加信息
        for (const key in obj) {
          const dom = document.querySelector(`#updateModal [name='${key}']`)
          if (key === 'sex') {
            document.querySelector(`#updateModal [name=sex][value=${obj.sex}]`).checked = true
            continue //跳过下面的程序
          }
          if (dom) {
            dom.value = obj[key]
          }
        }
        // 获取 市级 的下拉框内容
        renderSelect('/geo/city', {
          pname: obj.province
        }, document.querySelector('#updateModal [name=city]'), '市', obj.city)

        // 获取县级 下拉框内容
        renderSelect('/geo/county', {
          pname: obj.province,
          cname: obj.city
        }, document.querySelector('#updateModal [name=county]'), '县', obj.county)
      }
    })
  } else if (e.target.nodeName === 'BUTTON' && e.target.classList.contains('delectbtn')) {
    // 删除学生
    if (confirm('是否删除？')) {
      const id = e.target.dataset.id
      axios.delete('/student/delete', { params: { id: id } }).then(res => {
        if (res.data.code === 0) {
          toastr.success(res.data.message)
          // 获取最新的数据
          getstudentList();
        }
      })
    }

  }
})

// 点击修改按钮， 提交修改学生信息请求
upadteform.addEventListener("submit", function (e) {
  e.preventDefault();
  // 获取表单内容
  const data = $(upadteform).serialize()
  console.log(data);

  axios.put('/student/update', data).then(res => {
    if (res.data.code === 0) {
      toastr.success(res.data.message)
      // 关闭模态框
      $('#updateModal').modal('hide');
      // 获取最新的数据
      getstudentList();
    }
  })
})
